package com.chatplus.application.scheduled;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.chatplus.application.common.logging.SouthernQuietLogger;
import com.chatplus.application.common.logging.SouthernQuietLoggerFactory;
import com.chatplus.application.domain.entity.account.UserEntity;
import com.chatplus.application.service.account.UserProductLogService;
import com.chatplus.application.service.account.UserService;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 用户订阅定时任务
 */
@Component
public class UserSubsTaskJob {
    private static final SouthernQuietLogger LOGGER = SouthernQuietLoggerFactory.getLogger(UserSubsTaskJob.class);
    private final UserProductLogService userProductLogService;
    private final UserService userService;

    public UserSubsTaskJob(UserProductLogService userProductLogService, UserService userService) {
        this.userProductLogService = userProductLogService;
        this.userService = userService;
    }

    /**
     * 用户订阅没有给用户套餐做重置的操作
     */
    @XxlJob(value = "UserSubsTaskJob#subsJob")
    public void subsJob() {
        LOGGER.message("开始执行定时用户订阅重置任务").debug();
        LocalDateTime now = LocalDateTime.now();
        String resetDate = DateUtil.format(now, DatePattern.NORM_DATE_PATTERN);
        LambdaQueryWrapper<UserEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserEntity::getVipResetDate, resetDate);
        queryWrapper.ge(UserEntity::getVipExpiredTime, now);
        List<UserEntity> userList = userService.list(queryWrapper);
        if (CollectionUtils.isNotEmpty(userList)) {
            userList.forEach(user -> {
                LOGGER.message("开始执行定时用户订阅重置任务").context("userId", user.getId()).info();
                userProductLogService.resetSubscribeToUserByDaily(user.getId(), null);
                user.setVipResetDate(DateUtil.format(now.plusDays(1), DatePattern.NORM_DATE_PATTERN));
                userService.updateById(user);
            });
        }

    }
}
